import React, { Component } from 'react';
import { STORAGE_CONSTANT } from '../../config/storage';
import { GLOBAL } from '../../config/global';
import { UpdateModal } from '../../component/update/UpdateModal';
import StorageHelper from '../../utils/storageHelper';
import JsonUtils from '../../utils/JsonUtils';
var appInfo = require('react-native-device-info');

export class CheckUpdate extends Component {
	static props = {
		appVersionInfo: null
	}

	constructor(props) {
		super(props);
		this.state = {
			update: false
		};
	}

	componentWillMount () {
		this.getAppVersion();
	}

	//获取版本信息
	async getAppVersion () {
		let versionIgnore = await StorageHelper.get(STORAGE_CONSTANT.VERSION_IGNORE);
		versionIgnore = JsonUtils.stringToJson(versionIgnore) || {};
		this.versionIgnoreTime = new Date(versionIgnore['versionIgnoreTime']) || new Date(0);
		this.versionIgnoreCode = versionIgnore['versionIgnoreCode'] || 1;
		this.nowTime = new Date();
		this.currVersion = appInfo.getBuildNumber();   // versionCode
		if (this.props.appVersionInfo) {
			let pushTime = new Date(this.props.appVersionInfo['publishDate']);
			//如果最新版本大于当前版本，则继续
			if (this.props.appVersionInfo['versionCode'] && this.currVersion
				// && this.versionCompare(this.currVersion, this.props.appVersionInfo['versionCode'])) {
				&& (Number.parseFloat(this.props.appVersionInfo['versionCode']) > Number.parseFloat(this.currVersion))) {
				//标识是否需要更新--个人中心使用
				GLOBAL.APP_HAS_UPDATE = true;
				//最新版本大于上次忽略版本，则直接提示更新
				// if (this.versionCompare(this.versionIgnoreCode, this.props.appVersionInfo['versionCode'])) {
				if (Number.parseFloat(this.versionIgnoreCode) < Number.parseFloat(this.props.appVersionInfo['versionCode'])) {
					this.setState({ update: true });
				} else {
					if ((this.nowTime.valueOf() - this.versionIgnoreTime.valueOf()) >= GLOBAL.UPDATE_DETECT_INTERVAL) {
						//如果服务器返回的发布时间小于当前时间，则继续检查更新
						if (pushTime.valueOf() < this.nowTime.valueOf()) {
							this.setState({ update: true });
						}
					}
				}
			}
		}
	}

	//版本比较
	versionCompare (currVer, promoteVer) {
		currVer = currVer || "0.0.0";
		promoteVer = promoteVer || "0.0.0";
		if (currVer == promoteVer) return false;
		let currVerArr = currVer.split(".");
		let promoteVerArr = promoteVer.split(".");
		let len = Math.max(currVerArr.length, promoteVerArr.length);
		for (let i = 0; i < len; i++) {
			let proVal = ~~promoteVerArr[i],
				curVal = ~~currVerArr[i];
			if (proVal < curVal) {
				return false;
			} else if (proVal > curVal) {
				return true;
			}
		}
		return false;
	}

	render () {
		const { update } = this.state;
		return update ? (<UpdateModal appVersionInfo={this.props.appVersionInfo} />) : (null)
	}
}
